package com.kitty.game.pk.service;

import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.activity.service.ActivityHandler;
import com.kitty.game.config.GameMap;
import com.kitty.game.config.NPC;
import com.kitty.game.config.TalkSet;
import com.kitty.game.config.TaskSet;
import com.kitty.game.confirm.model.AcceptKillTaskConfirm;
import com.kitty.game.confirm.model.ForcePKConfirm;
import com.kitty.game.confirm.model.GotoFPKConfirm;
import com.kitty.game.confirm.model.PrisonReleaseConfirm;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.ReqTelePort;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.pk.message.RespPkInfo;
import com.kitty.game.pk.message.RespPrisonerInfo;
import com.kitty.game.pk.message.RespReleasePrisonerSuccess;
import com.kitty.game.pk.message.RespZuolaoInfoFinish;
import com.kitty.game.pk.message.vo.ForcePkRecord;
import com.kitty.game.pk.message.vo.PrisonerInfo;
import com.kitty.game.pk.model.PkRecord;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.scene.SceneManager;
import com.kitty.game.school.model.SchoolSet;
import com.kitty.game.school.service.SchoolService;
import com.kitty.game.talk.service.TalkService;
import com.kitty.game.task.TaskDataPool;
import com.kitty.game.task.message.vo.TaskInfo;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.task.service.taskHandler.ForcePkTaskHandler;
import com.kitty.game.team.message.RespConfirm;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.EnterMapEvent;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.listener.event.LeaveMapEvent;
import com.kitty.listener.event.PkValueChangeEvent;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.task.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

@Service
public class PkService extends ActivityHandler {
    @Autowired
    TalkService talkService;
    @Autowired
    NewTaskService taskService;
    @Autowired
    RoleService roleService;
    @Autowired
    TeamService teamService;
    @Autowired
    FightService fightService;
    @Autowired
    RedisService redisService;

    /** PK开启的确认提示
     * 凝聚杀气需花费#cFF2020100,394,030#n文钱#n，确认继续吗？
     * 由于你今日活跃不足100，需额外花费#cFF2020100,000,000#n文钱#n。*/


    /**发送PK规则*/
    public void sendPkRules(Role role) {
        TalkSet talkSet =talkService.getTalkSet(1270,role);
        talkService.popFirstTalk(role, talkSet);
    }

    /**接取任务*/
    public void acceptKillTask(Role role, NPC npc) {
        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.KILL_TASKID, role);
        if (taskService.isTaskAccepted(role, taskSet)) {
            String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1101, taskSet.getTaskName());
            teamService.pushMessage(role, new RespMsg(content));
            return ;
        }

        int money = getPkMoney(role);
        String moneyFormat = AsktaoUtil.getMoneyFormat(money);
        String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1125, moneyFormat);

        RespConfirm respConfirm = new RespConfirm();
        respConfirm.setTips(content);
        MessagePusher.pushMessage(role, respConfirm);

        role.setConfirm(new AcceptKillTaskConfirm());
    }

    /**确认接取任务*/
    public void confirmAcceptKillTask(Role role) {
        int money = getPkMoney(role);
        if (role.getMoney() < money) {
            MessagePusher.notify2Player(role, I18nId.PMT_401);
            return ;
        }if (role.getLevel() < Const.FORCEPK_MIN_LEVEL) {
            MessagePusher.notify2Player(role, I18nId.PMT_1116, Const.FORCEPK_MIN_LEVEL);
            return ;
        }

        /**扣除金钱*/
        SpringUtils.getRoleService().subtractMoney(role, money, Reason.ACCEPT_KILL_TASK);

        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.KILL_TASKID, role);
        SpringUtils.getBean(ForcePkTaskHandler.class).acceptTask(role, taskSet);
    }

    /**
     * 请求强制PK
     */
    public void reqForcePK(Role role, Role targetRole) {
        /**未接取任务时，弹出确认框*/
        if (!role.getTask().isAccepted(TaskDataPool.KILL_TASKID)) {
            TaskSet taskSet = taskService.getTaskSet(TaskDataPool.KILL_TASKID, role);
            String qiangp_jifen = DataCache.REDIS_DATA.get("qiangp_jifen");
            //int money = Integer.parseInt(qiangp_jifen);// getPkMoney(role);
            String moneyFormat = AsktaoUtil.getMoneyFormat(Integer.parseInt(qiangp_jifen));
            String content = String.format("未领取#R%s#n任务,需花%s积分才能强P，你确认要#RPK#n玩家#Y%s#n吗？", taskSet.getTaskName(), moneyFormat, targetRole.getName());
//            String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1100, taskSet.getTaskName(), moneyFormat, targetRole.getName());

            RespConfirm respConfirm = new RespConfirm();
            respConfirm.setTips(content);
            MessagePusher.pushMessage(role, respConfirm);

            role.setConfirm(new ForcePKConfirm(targetRole.getUid()));
            return ;
        }

        String check = checkBeforeForcePK(role, targetRole);
        if (check != null) {
            SpringUtils.getTeamService().pushMessage(role, new RespMsg(check));
            return ;
        }
        doForcePK(role, targetRole);
    }

    private String checkBeforeForcePK(Role role, Role targetRole) {
        if (targetRole == null) {
            return I18nIdDataPool.getI18nContent(I18nId.PMT_1114);
        }
        if (targetRole.getLevel() < Const.FORCEPK_MIN_LEVEL) {
            return I18nIdDataPool.getI18nContent(I18nId.PMT_1115, Const.FORCEPK_MIN_LEVEL);
        }
        if (role.getLevel() < Const.FORCEPK_MIN_LEVEL) {
            return I18nIdDataPool.getI18nContent(I18nId.PMT_1116, Const.FORCEPK_MIN_LEVEL);
        }
        GameMap targetMap = SpringUtils.getMapService().getMap(targetRole.getPos().getMapId());
        if (targetMap.isSafe_zone()) {
            return I18nIdDataPool.getI18nContent(I18nId.PMT_1110);
        }
        if (isInForcePkProtectTime()) {
            String not_pk_time = DataCache.REDIS_DATA.get("not_pk_time");
            return not_pk_time+"期间无法发起PK。";
        }
        return null;
    }

    private int getPkMoney(Role role) {
        long money = Const.FORCKPK_INIT_MONEY + (role.getPkInfoBox().getPkValue()*Const.FORCKPK_ADD_MONEY);
        if (money > Const.FORCEPK_MAX_MONEY) {
            money = Const.FORCEPK_MAX_MONEY;
        }
        return (int) money;
    }

    /**确认强制PK*/
    public void confirmForcePK(Role role, long targetUid) {
        Role targetRole = roleService.getOnlinePlayer(targetUid);
        String check = checkBeforeForcePK(role, targetRole);
        if (check != null) {
            SpringUtils.getTeamService().pushMessage(role, new RespMsg(check));
            return ;
        }
        if (role.getPos().getMapId() != targetRole.getPos().getMapId()) {
            MessagePusher.notify2Player(role, I18nId.PMT_1117);
            return ;
        }
//        if (role.getMoney() < getPkMoney(role)) {
//            MessagePusher.notify2Player(role, I18nId.PMT_401);
//            return ;
//        }
        int subScore = Integer.parseInt(DataCache.REDIS_DATA.get("qiangp_jifen"));
        roleService.substractChargeScore(role, subScore);

        /**扣除金钱*/
        //int needMoney =200000;// getPkMoney(role);
//        SpringUtils.getRoleService().substractChargeScore(role, needMoney);
        //roleService.subGoldOrCharge(role,subScore,Reason.BUY_ITEM);
        MessagePusher.pushMessage(role,new RespNotifyMiscEx("扣除"+subScore+"积分，开启强P成功"));
        doForcePK(role, targetRole);
    }

    /**执行强制PK*/
    private void doForcePK(Role role, Role pkRole) {
//        if (true){
//            MessagePusher.pushMessage(role,new RespNotifyMiscEx("强pk维护中。。。"));
//            return;
//        }
        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.KILL_TASKID, role);
        if (taskService.isTaskAccepted(role, taskSet)) {
            /**已接杀气腾腾任务，开始PK时删除任务，同时提示*/
            SpringUtils.getBean(ForcePkTaskHandler.class).forceResetTask(role, taskSet);
            MessagePusher.notifyMisc2Player(role, I18nId.PMT_1102);
        }
        teamService.memberHandle(role, memberRole -> MessagePusher.notifyMisc2Player(memberRole, I18nId.PMT_1103, pkRole.getName()));
        teamService.memberHandle(role, memberRole -> MessagePusher.notify2Player(memberRole, I18nId.PMT_1123, pkRole.getName()));

        teamService.memberHandle(pkRole, memberRole -> MessagePusher.notifyMisc2Player(memberRole, I18nId.PMT_1104, role.getName()));
        teamService.memberHandle(pkRole, memberRole -> MessagePusher.notify2Player(memberRole, I18nId.PMT_1124, role.getName()));

        Team team = teamService.getTeam(role.getRoleId());
        Team pkTeam = teamService.getTeam(pkRole.getRoleId());

        if (team != null && pkTeam != null) {// 都组队
            if (team.getId() == pkTeam.getId()) {
                return;
            }
            fightService.enterTeamForcePK(team.getList(), pkTeam.getList(), role);
        } else if (team != null) {// 对方没有组队 己方组队
            ArrayList<Member> arrayList = new ArrayList<>();
            Member member = Member.valueOf(pkRole);
            arrayList.add(member);
            fightService.enterTeamForcePK(team.getList(), arrayList, role);
        } else if (pkTeam != null) {// 对方组队 己方没有组队
            ArrayList<Member> arrayList = new ArrayList<>();
            Member member = Member.valueOf(role);
            arrayList.add(member);
            fightService.enterTeamForcePK(arrayList, pkTeam.getList(), role);
        } else {// 都没有组队
            ArrayList<Member> arrayListA = new ArrayList<>();
            Member memberA = Member.valueOf(role);
            arrayListA.add(memberA);

            ArrayList<Member> arrayListB = new ArrayList<>();
            Member memberB = Member.valueOf(pkRole);
            arrayListB.add(memberB);
            fightService.enterTeamForcePK(arrayListA, arrayListB, role);
        }
    }



    @Override
    public void handleFightEnd(FightEndEvent fightEndEvent) {
        doFightEnd(fightEndEvent.getRole(), fightEndEvent);
    }

    public void doFightEnd(Role role, FightEndEvent fightEndEvent) {
        if (!isMatchFightType(role, fightEndEvent.getFightType())) {
            return ;
        }

        switch (fightEndEvent.getStatus()) {
            case FightEndEvent.WIN:
                doFightWin(role, fightEndEvent);
                break;
            case FightEndEvent.FAIL:
                doFightFail(role, fightEndEvent);
                break;
            case FightEndEvent.RUNAWAY:
                doFightRunAway(role, fightEndEvent);
                doFightFail(role, fightEndEvent);
                break;
            case FightEndEvent.MAXROUND:
                doFightMaxRound(role, fightEndEvent);
                break;
        }
    }

    /**是否匹配战斗类型*/
    private boolean isMatchFightType(Role role, int fightType) {
        return getFightType(role) == fightType;
    }

    private int getFightType(Role role) {
        return Const.fightType_forcePK;
    }

    /**处理战斗胜利*/
    public void doFightWin(Role role, FightEndEvent fightEndEvent) {
        if (role.getLastDead() == 0) {
            teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
            return;
        }
        if(!isASide(role, fightEndEvent.getRolesA())){
            SpringUtils.getBean(RoleService.class).addAchieveScore(role,"104002");
        }
        if (isASide(role, fightEndEvent.getRolesA()) && !isAllRedName(fightEndEvent.getRolesB())) {
            /**发起方胜利且被PK方不都是红名状态时*/
            role.getPkInfoBox().setRedName(true);
            SpringUtils.getBean(RoleService.class).addAchieveScore(role,"104001");
            int pkValue = 1;
            if (!teamService.isInTeam(role) || teamService.isTeamLeader(role)) {
                pkValue = 2;
            }
            if (isDoublePkValue(fightEndEvent.getRolesA(), fightEndEvent.getRolesB())) {
                pkValue = pkValue * 2;
            }
            role.getPkInfoBox().setPkValue(role.getPkInfoBox().getPkValue() + pkValue);
            role.getPkInfoBox().setRedTime((int) (role.getPkInfoBox().getRedTime() + (Const.WIN_ADD_RED_HOUR * TimeUtil.ONE_HOUR / TimeUtil.ONE_SECOND)));
            role.save();
            /** 产生一个pk值改变事件 */
            EventDispatcher.getInstance().fireEvent(new PkValueChangeEvent(EventType.PK_VALUE_CHANGE, role, role.getPkInfoBox().getPkValue()));

            SpringUtils.getBroadcastService().sendUpdateAppear(role);

            TaskSet taskSet = taskService.getTaskSet(TaskDataPool.RED_TASKID, role);
            if (!taskService.isTaskAccepted(role, taskSet)) {
                SpringUtils.getBean(ForcePkTaskHandler.class).acceptTask(role, taskSet);
            } else {
                TaskInfo taskInfo = SpringUtils.getBean(ForcePkTaskHandler.class).getTaskInfo(role, taskSet);
                taskService.pushTaskInfo(role, taskInfo);
            }

            MessagePusher.notifyMisc2Player(role, I18nId.PMT_1122, Const.WIN_ADD_RED_HOUR, pkValue, role.getPkInfoBox().getPkValue(), Const.TRANSFER_PRISON_PKVALUE);

            checkAfterWin(role);
        }
    }

    /**
     * 是否主动PK方
     */
    public boolean isASide(Role role, List<Role> rolesA) {
        if (rolesA != null) {
            for (Role roleA : rolesA) {
                if (role.getUid() == roleA.getUid()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**是否所有成员都是红名状态*/
    private boolean isAllRedName(List<Role> roles) {
        if (roles != null) {
            for (Role role : roles) {
                if (!role.getPkInfoBox().isRedName()) {
                    return false;
                }
            }
        }
        return true;
    }

    /**是否pk值需要翻倍*/
    private boolean isDoublePkValue(List<Role> rolesA, List<Role> rolesB) {
        /**被PK方有任意玩家等级小于PK方任意玩家等级29级，则PK方所有玩家获得PK值翻倍*/
        int maxLevelA = 0;
        for (Role role : rolesA) {
            if (role.getLevel() > maxLevelA) {
                maxLevelA = role.getLevel();
            }
        }

        int minLevelB = 0;
        for (Role role : rolesB) {
            if (minLevelB == 0 || role.getLevel() < minLevelB) {
                minLevelB = role.getLevel();
            }
        }

        return maxLevelA >= minLevelB + 29;
    }

    /**处理战斗失败*/
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        roleService.punishFightDead(role);
        ReqTelePort reqTelePort = new ReqTelePort();
        reqTelePort.setMapId(1000);
        reqTelePort.setX(25);
        reqTelePort.setY(110);
        SpringUtils.getMapService().changeMap(role, reqTelePort);

        if (!teamService.isInTeam(role) || teamService.isTeamLeader(role)) {
            Role killRole = null;
            if (isASide(role, fightEndEvent.getRolesA())) {
                killRole = getOperRole(fightEndEvent.getRolesB());
            } else {
                killRole = getOperRole(fightEndEvent.getRolesA());
            }
            if (killRole != null) {
                /**提示被杀信息*/
                MessagePusher.notify2Player(role, I18nId.PMT_1105, killRole.getName());

                /**杀记录*/
                addKillRole(killRole, role);

                /**被杀记录*/
                addBeKillRole(role, killRole);
            }
        }
    }

    /**加入杀记录*/
    private void addKillRole(Role role, Role targetRole) {
        if (role.getPkInfoBox().getKillRoles() == null) {
            role.getPkInfoBox().setKillRoles(new HashMap<>());
        }
        int now = (int) (System.currentTimeMillis() / TimeUtil.ONE_SECOND);
        PkRecord pkRecord = new PkRecord(targetRole.getUid(), targetRole.getName(), targetRole.getRoleIcon(), targetRole.getLevel(), targetRole.getPolar(), now);
        role.getPkInfoBox().getKillRoles().put(pkRecord.getUid(), pkRecord);
    }

    /**加入被杀记录*/
    private void addBeKillRole(Role role, Role targetRole) {
        if (role.getPkInfoBox().getBeKillRoles() == null) {
            role.getPkInfoBox().setBeKillRoles(new HashMap<>());
        }
        int now = (int) (System.currentTimeMillis() / TimeUtil.ONE_SECOND);
        PkRecord pkRecord = new PkRecord(targetRole.getUid(), targetRole.getName(), targetRole.getRoleIcon(), targetRole.getLevel(), targetRole.getPolar(), now);
        role.getPkInfoBox().getBeKillRoles().put(pkRecord.getUid(), pkRecord);
    }

    /**获得操作的Role对象,组队时返回队长*/
    private Role getOperRole(List<Role> roles) {
        if (roles != null && roles.size() > 0) {
            if (roles.size() == 1) {
                return roles.get(0);
            } else {
                for (Role role : roles) {
                    if (teamService.isTeamLeader(role)) {
                        return role;
                    }
                }
            }
        }
        return null;
    }

    /**处理战斗逃跑*/
    public void doFightRunAway(Role role, FightEndEvent fightEndEvent) {

    }

    /**处理战斗超过最大回合数*/
    public void doFightMaxRound(Role role, FightEndEvent fightEndEvent) {
        if (isASide(role, fightEndEvent.getRolesA())) {
            /**主动PK方受到死亡惩罚*/
            roleService.punishFightDead(role);
        }
    }

    /**是否在坐牢期间*/
    public boolean isInPrisonTime(Role role) {
        return role.getPkInfoBox().getPrisonTime() > 0;
    }

    /**切换地图检测是否进入监狱*/
    public void checkEnterMap(Role role) {
        teamService.memberHandle(role, memberRole -> {
            if (isNeedInPrison(memberRole)) {
                add2Prison(memberRole);
            }
        });
    }

    /**胜利时检查是否进入监狱*/
    public void checkAfterWin(Role role) {
        teamService.memberHandle(role, memberRole -> {
            if (isNeedInPrison(memberRole)) {
                add2Prison(memberRole);
            }
        });
    }

    /**是否需要进入监狱*/
    private boolean isNeedInPrison(Role role) {
        /**已经在监狱，不需要抓进监狱*/
        if (SpringUtils.getMapService().isInMap(role, Const.PRISON_MAPID)) {
            return false;
        }
        if (role.getPkInfoBox().isRedName()) {
            int mapId = role.getPos().getMapId();
            GameMap map = SpringUtils.getMapService().getMap(mapId);
            if (map.isSafe_zone()) {
                /**红名进入安全区，抓进监狱*/
                return true;
            }
            if (role.getPkInfoBox().getPkValue() > Const.TRANSFER_PRISON_PKVALUE) {
                /**红名和PK值大于40，抓进监狱*/
                return true;
            }
        }
        return false;
    }

    /**关入监狱*/
    public void add2Prison(Role role) {
        /**组队时先离队*/
        if (teamService.isInTeam(role)) {
            teamService.leave(role, false);
        }

        ReqTelePort reqTelePort = new ReqTelePort();
        reqTelePort.setMapId(Const.PRISON_MAPID);
        reqTelePort.setX(31);
        reqTelePort.setY(18);
        SpringUtils.getMapService().changeMap(role, reqTelePort);
        SceneManager.INSTANCE.sendMessages(role, new Message[]{SpringUtils.getBean(BroadcastService.class).getUpdateAppear(role)});
        role.getPkInfoBox().setPrisonTime((int) ( System.currentTimeMillis() / 1000+(TimeUtil.ONE_HOUR/1000)));

        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.PRISON_TASKID, role);
        SpringUtils.getBean(ForcePkTaskHandler.class).acceptTask(role, taskSet);

        TalkSet talkSet =talkService.getTalkSet(1280,role);
        talkService.popFirstTalk(role, talkSet);
    }

    /**放出监狱*/
    public void removeFromPrison(Role role) {
        role.getPkInfoBox().setRedName(false);
        role.getPkInfoBox().setRedTime(0);
        role.getPkInfoBox().setPrisonTime(0);

        ReqTelePort reqTelePort = new ReqTelePort();
        reqTelePort.setMapId(Const.PRISON_MAPID);
        reqTelePort.setX(32);
        reqTelePort.setY(28);
        SpringUtils.getMapService().changeMap(role, reqTelePort);

        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.PRISON_TASKID, role);
        SpringUtils.getBean(ForcePkTaskHandler.class).forceResetTask(role, taskSet);
    }

    /**查看在押犯人*/
    public void viewPrisoner(Role role, NPC npc) {
        SpringUtils.getNpcService().openDlg(role, "PrisonDlg");

        RespPrisonerInfo respPrisonerInfo = getRespPrisonerInfo();
        MessagePusher.pushMessage(role, respPrisonerInfo);

        MessagePusher.pushMessage(role, new RespZuolaoInfoFinish());
    }

    /**在押犯人客户端返回包*/
    private RespPrisonerInfo getRespPrisonerInfo() {
        RespPrisonerInfo respPrisonerInfo = new RespPrisonerInfo();
        List<PrisonerInfo> prisonerInfos = new ArrayList<>();
        respPrisonerInfo.setPrisonerInfos(prisonerInfos);

        List<Role> prisonRoles = getPrisonRoles();
        PrisonerInfo prisonerInfo = null;
        for (Role role : prisonRoles) {
            prisonerInfo = new PrisonerInfo();
            prisonerInfo.setGid(String.valueOf(role.getGid()));
            prisonerInfo.setName(role.getName());
            prisonerInfo.setLevel(role.getLevel());
            SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
            SchoolSet schoolSet = schoolService.getShoolSet((byte) role.getPolar());
            GameMap outMap = SpringUtils.getMapService().getMap(schoolSet.getOuterMap());
            GameMap innerMap = SpringUtils.getMapService().getMap(schoolSet.getInnerMap());
            prisonerInfo.setFamily(outMap.getName() + innerMap.getName());
            prisonerInfo.setPolar(role.getPolar());
            String sonName = SpringUtils.getBean(ServerService.class).getServer().getSonName();
            prisonerInfo.setServerName(sonName);
            int remainTime = (int)((role.getPkInfoBox().getPrisonTime()-(System.currentTimeMillis()/1000)));
            prisonerInfo.setLastTi((int)remainTime);

            prisonerInfos.add(prisonerInfo);
        }

        return respPrisonerInfo;
    }

    /**获得在线的在押犯人玩家*/
    public List<Role> getPrisonRoles() {
        List<Role> prisonRoles = new ArrayList<>();
        DataCache.ONLINE_ROLES.values().forEach(role -> {if (role.getPkInfoBox().getPrisonTime() > 0) { prisonRoles.add(role); }});
        return prisonRoles;
    }

    /**求情*/
    public void pleadForPrisoner(Role role, long gid, String name) {
        MessagePusher.notify2Player(role, I18nId.PMT_1106);
    }

    /**保释*/
    public void releasePrisoner(Role role, long gid, String name) {
        if(role.getLevel()>80){
            role.setConfirm(new PrisonReleaseConfirm(gid, name));
            //String moneyFormat = AsktaoUtil.getMoneyFormat(Const.PRISON_RELEASE_MONEY);
            String jianyu_sbaoshi = DataCache.REDIS_DATA.get("jianyu_sbaoshi");
            String msg = "确认花费%s积分保释#Y%s#n吗？";
            String content =String.format(msg, jianyu_sbaoshi, name);
            RespConfirm respConfirm = new RespConfirm();
            respConfirm.setTips(content);
            MessagePusher.pushMessage(role, respConfirm);
        }else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("等级不足80级，无法保释"));
        }
    }

    /**确认保释*/
    public void confirmReleasePrisoner(Role role, long gid, String name) {
        Role targetRole = SpringUtils.getRoleService().getOnlinePlayer(gid);
        if (targetRole == null) {
            return ;
        }
        if (!isInPrisonTime(targetRole)) {
            MessagePusher.notify2Player(role, I18nId.PMT_1108, targetRole.getName());
            return ;
        }
        int subScore = Integer.parseInt(DataCache.REDIS_DATA.get("jianyu_sbaoshi"));
        roleService.substractChargeScore(role, subScore);
//        roleService.subGoldOrCharge(role,Const.PRISON_RELEASE_MONEY,Reason.BUY_ITEM);
//        if (role.getMoney() < Const.PRISON_RELEASE_MONEY) {
//            MessagePusher.notify2Player(role, I18nId.PMT_401);
//            return ;
//        }


        /**扣除金钱*/
        //SpringUtils.getRoleService().subtractMoney(role, Const.PRISON_RELEASE_MONEY, Reason.PRISON_RELEASE);

        //SpringUtils.getRoleService().substractChargeScore(role,2);

        /**放出监狱*/
        removeFromPrison(targetRole);

        MessagePusher.pushMessage(role, new RespReleasePrisonerSuccess(targetRole.getGid()));
    }

    /**打开追踪界面*/
    public void openSearchDialog(Role role, NPC npc) {
        SpringUtils.getNpcService().openDlg(role, "SearchUserDlg");
    }

    public void viewForcePkInfo(Role role, String type, String para1, String para2) {
        RespPkInfo respPkInfo = new RespPkInfo();
        respPkInfo.setType(type);
        List<ForcePkRecord> pkRecords = new ArrayList<>();
        respPkInfo.setPkInfoList(pkRecords);

        if ("pk_record".equals(type)) {
            /**我杀的*/
            if (role.getPkInfoBox().getKillRoles() != null) {
                for (PkRecord pkRecord : role.getPkInfoBox().getKillRoles().values()) {
                    pkRecords.add(getForcePkRecord(pkRecord));
                }
            }
        } else if ("be_pk_record".equals(type)) {
            /**杀我的*/
            if (role.getPkInfoBox().getBeKillRoles() != null) {
                for (PkRecord pkRecord : role.getPkInfoBox().getBeKillRoles().values()) {
                    pkRecords.add(getForcePkRecord(pkRecord));
                }
            }
        } else if ("search_pk".equals(type)) {
            /**搜索*/
            Role targetRole = null;
            int p2 = Integer.parseInt(para2);
            if (p2 == 1) {
                String name = para1;
                targetRole = SpringUtils.getRoleService().getOnlinePlayer(name);
            } else if (p2 == 2) {
                long uid = Long.parseLong(para1);
                targetRole = roleService.getOnlinePlayer(uid);
            }

            if (targetRole == null) {
                MessagePusher.notify2Player(role, I18nId.PMT_1111);
                return ;
            }

            pkRecords.add(getForcePkRecord(targetRole));
        }

        MessagePusher.pushMessage(role, respPkInfo);
    }

    private ForcePkRecord getForcePkRecord(PkRecord pkRecord) {
        ForcePkRecord record = new ForcePkRecord();
        record.setGid(String.valueOf(pkRecord.getUid()));
        record.setUpdateTime(String.valueOf(pkRecord.getTime()));
        String sonName = SpringUtils.getBean(ServerService.class).getServer().getSonName();
        record.setServerName(roleService.isOnline(pkRecord.getUid()) ? sonName : "");
        record.setList(new ArrayList<>());
        List<FiedValue> list = record.getList();
        list.add(new FiedValue(305, String.valueOf(pkRecord.getUid())));
        list.add(new FiedValue(1, pkRecord.getName()));
        list.add(new FiedValue(40, pkRecord.getIcon()));
        list.add(new FiedValue(31, pkRecord.getLevel()));
        return record;
    }

    private ForcePkRecord getForcePkRecord(Role role) {
        ForcePkRecord record = new ForcePkRecord();
        record.setGid(String.valueOf(role.getUid()));
        record.setUpdateTime(String.valueOf(System.currentTimeMillis()/TimeUtil.ONE_SECOND));
        String sonName = SpringUtils.getBean(ServerService.class).getServer().getSonName();
        record.setServerName(roleService.isOnline(role.getUid()) ? sonName : "");
        record.setList(new ArrayList<>());
        List<FiedValue> list = record.getList();
        list.add(new FiedValue(305, String.valueOf(role.getUid())));
        list.add(new FiedValue(1, role.getName()));
        list.add(new FiedValue(40, role.getRoleIcon()));
        list.add(new FiedValue(31, role.getLevel()));
        return record;
    }

    /**传送强制PK*/
    public void transferForcePk(Role role, long uid) {
        Role targetRole = roleService.getOnlinePlayer(uid);
        if (targetRole == null) {
            MessagePusher.notify2Player(role, I18nId.PMT_1109);
        }
        GameMap targetMap = SpringUtils.getMapService().getMap(targetRole.getPos().getMapId());
        if (targetMap == null) {
            return ;
        }
        if (targetMap.isSafe_zone()) {
            MessagePusher.notify2Player(role, I18nId.PMT_1110);
            return;
        }

        int needMoney = getPkMoney(role);
        String moneyFormat = AsktaoUtil.getMoneyFormat(needMoney);
        String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1112, moneyFormat, targetRole.getName());

        RespConfirm respConfirm = new RespConfirm();
        respConfirm.setTips(content);
        SpringUtils.getTeamService().pushMessage(role, respConfirm);

        role.setConfirm(new GotoFPKConfirm(targetRole.getUid()));
    }

    /**确认传送并开始强制PK*/
    public void confirmTransferForcePk(Role role, long targetUid) {
        Role targetRole = roleService.getOnlinePlayer(targetUid);
        String check = checkBeforeForcePK(role, targetRole);
//        if (true){
//            return;
//        }
        if (check != null) {
            MessagePusher.pushMessage(role, new RespMsg(check));
            return ;
        }
        if (role.getMoney() < getPkMoney(role)) {
            MessagePusher.notify2Player(role, I18nId.PMT_401);
            return ;
        }
        if (fightService.canFight(role, null) == false) {
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("你正在战斗中，不能追踪"));
            return;
        }
        if (fightService.canFight(targetRole, null) == false) {
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("目标正在战斗中，不能追踪"));
            return;
        }

        int needMoney = getPkMoney(role);
        roleService.subtractMoney(role, needMoney, Reason.GOTO_FFK);
//        roleService.substractChargeScore(role,10);
//        MessagePusher.pushMessage(role,new RespNotifyMiscEx("扣除10积分"));

        transferTargetPos(role, targetRole);

        ThreadLocalUtil.addLocalTask(role, () -> doForcePK(role, targetRole));

    }

    private void transferTargetPos(Role role, Role targetRole) {
        if (role.getPos().getMapId() != targetRole.getPos().getMapId()) {
            int oldMapId = role.getPos().getMapId();
            /**产生一个离开地图事件*/
            EventDispatcher.getInstance().fireEvent(new LeaveMapEvent(EventType.LEAVE_MAP, role, role.getPos().getMapId()));

            role.setPos(targetRole.getPos().getX(), targetRole.getPos().getY(), targetRole.getPos().getDir(), targetRole.getPos().getMapId());
            /**产生一个进入地图事件*/
            EventDispatcher.getInstance().fireEvent(new EnterMapEvent(EventType.ENTER_MAP, role,oldMapId));
        } else {
            /**如果在一个地图 移动到目标身边*/
            role.setPos(targetRole.getPos().getX(), targetRole.getPos().getY(), targetRole.getPos().getDir(), targetRole.getPos().getMapId());
            SceneManager.INSTANCE.movePosition(role);
        }
    }

    /**是否是在pk保护时间阶段*/
    private boolean isInForcePkProtectTime() {
        // 18:30-20:30
        Calendar now = Calendar.getInstance();
        String not_pk_time = DataCache.REDIS_DATA.get("not_pk_time");
        String start = not_pk_time.split("-")[0];

        String end = not_pk_time.split("-")[1];
        Calendar setCal = Calendar.getInstance();
        setCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(start.split(":")[0]));
        setCal.set(Calendar.MINUTE, Integer.parseInt(start.split(":")[1]));
        setCal.set(Calendar.SECOND, 0);
        setCal.set(Calendar.MILLISECOND, 0);

        if (now.before(setCal)) {
            return false;
        }

        setCal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(end.split(":")[0]));
        setCal.set(Calendar.MINUTE, Integer.parseInt(end.split(":")[1]));
        setCal.set(Calendar.SECOND, 0);
        setCal.set(Calendar.MILLISECOND, 0);
        if (now.after(setCal)) {
            return false;
        }

        return true;
    }

    /**清除罪孽*/
    public void clearForcePkValue(Role role, NPC npc) {
        if (role.getPkInfoBox().getPkValue() <= 0) {
            String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1120);
            SpringUtils.getNpcService().sendNpcContent(role, npc, content);
            return ;
        }

        int money = getClearPkMoney(role);
        String moneyFormat = AsktaoUtil.getMoneyFormat(money);
        String content = I18nIdDataPool.getI18nContent(I18nId.PMT_1119, moneyFormat);
        SpringUtils.getNpcService().sendNpcContent(role, npc, content);
    }

    private int getClearPkMoney(Role role) {
        return 20000000;
    }

    /**捐香火钱*/
    public void donatePkValueMoney(Role role, NPC npc) {
        int money = getClearPkMoney(role);
        if (role.getMoney() < money) {
            MessagePusher.notify2Player(role, I18nId.PMT_401);
            return ;
        }

        roleService.subtractMoney(role, money, Reason.CLEAR_PKVALUE);
        roleService.substractChargeScore(role,2);
        MessagePusher.pushMessage(role,new RespNotifyMiscEx("扣除2点积分"));
        roleService.substractForcePkValue(role, 1);

        String moneyFormat = AsktaoUtil.getMoneyFormat(money);
        MessagePusher.notifyMiscEx2Player(role, I18nId.PMT_1121, moneyFormat, role.getPkInfoBox().getPkValue());

        TaskSet taskSet = taskService.getTaskSet(TaskDataPool.RED_TASKID, role);
        SpringUtils.getBean(ForcePkTaskHandler.class).pushTask(role, taskSet);
    }
}
